package com.wb3.meta.common.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wb3.meta.common.constant.CommonConstant;
import com.wb3.meta.common.enums.EnumRedisKey;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class HttpUtils {


    public static String upload(String url, File file, String filename, String empNo, String systemId) {
        String body = null;
//        String url = "http://10.1.8.154:2212/files";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httppost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000).build();
            httppost.setConfig(requestConfig);
            FileBody bin = new FileBody(file);
            StringBody comment = new StringBody(filename, ContentType.TEXT_PLAIN);
            StringBody userId = new StringBody(empNo, ContentType.TEXT_PLAIN);
            StringBody sysId = new StringBody(systemId, ContentType.TEXT_PLAIN);
            HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("file", bin).addPart("filename", comment)
                    .addPart("userId", userId)
                    .addPart("sysId", sysId).build();
            httppost.setEntity(reqEntity);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    body = EntityUtils.toString(response.getEntity());
                }
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return body;
    }

    public static File multipartFileToFile(MultipartFile file) throws IOException {

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * // Post请求
     *
     * @param url
     * @return
     */
    public static String post(String url, Map<String, String> headers, Map<String, String> paramMap, boolean openProxy) {
        String responseContent = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            //通过SchemeRegistry将SSLSocketFactory注册到我们的HttpClient上
            HttpPost httpPost = new HttpPost(url);
            if (headers != null) {
                for (String string : headers.keySet()) {
                    httpPost.setHeader(string, headers.get(string));
                }
            }
            List<NameValuePair> formParams = new ArrayList<NameValuePair>(); // 构建POST请求的表单参数
            for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));

            if (openProxy) {
                HttpHost proxy = new HttpHost("localhost", 7890);
                RequestConfig requestConfig = RequestConfig.custom()
                        .setProxy(proxy)
                        .setConnectTimeout(10000)
                        .setSocketTimeout(10000)
                        .setConnectionRequestTimeout(3000)
                        .build();
                httpPost.setConfig(requestConfig);
            } else {
                RequestConfig requestConfig = RequestConfig.custom()
                        .setConnectTimeout(10000)
                        .setSocketTimeout(10000)
                        .setConnectionRequestTimeout(3000)
                        .build();
                httpPost.setConfig(requestConfig);
            }
            HttpResponse response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity(); // 获取响应实体
            if (entity != null) {
                responseContent = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            httpclient.getConnectionManager().shutdown();
        }
        return responseContent;
    }


    public static String toHttp(String subscribeUrl, String msgJson) {
        BufferedInputStream bis = null;
        ByteArrayOutputStream buf = null;
        try {
            OutputStreamWriter out;
            URL url = new URL(subscribeUrl);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.connect();
            out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
            out.append(msgJson);
            out.flush();
            out.close();

            bis = new BufferedInputStream(connection.getInputStream());
            buf = new ByteArrayOutputStream();
            int result2 = bis.read();
            while (result2 != -1) {
                buf.write((byte) result2);
                result2 = bis.read();
            }
            String result = buf.toString();
            log.info("callBackAsyncSend url:{}, param:{}, res :{}", subscribeUrl, msgJson, result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("http error URL:{}, paramMap:{}", subscribeUrl, msgJson);
            return subscribeUrl + CommonConstant.errorTag + msgJson;
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (buf != null) {
                try {
                    buf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @SuppressWarnings("deprecation")
    public static String post(String url, String data) {

        String body = null;
        HttpClient hc = null;
        try {
            // Post请求
            HttpPost httppost = new HttpPost(url);
            httppost.addHeader("Content-Type", "application/json; charset=UTF-8;");
//            httppost.addHeader("token", "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJhODBlYmY4NS04YjcxLTQzNzEtODQ3MC1kZjBkNmYwMGQyOGQiLCJpYXQiOjE2NTQ1NzIwNDIsInN1YiI6IntcImFkZHJlc3NcIjpcIjB4MDg1ZEYwNzYzMzExMEMzRjljNjVBMTM3Rjk3NTJjRmU0NGMxNzZBOFwiLFwibWVzc2FnZVwiOlwiaGVsbG8gd29ybGRcIixcInNpZ25hdHVyZVwiOlwiMHhlYTcwOThiNDA3ZTE2MGYyMDBjNzE4NWYwYTk1YTlkNGM3YjIwMGQ1ZTJhNjNjZjljNTdmYTYwMjE2OWYzNWJkNDc4OTFmZmJkZTYxNjk0NTIyMmJkZWI2NDlmZTY4OGFkZjkxMzJlYWQ0YmFhZjVhMzUxZWQ3NWNlNjBmNThkYjFjXCJ9IiwiZXhwIjoxNjU0NTcyNjQyfQ.L5p7bV1ns8dnQGUq1WVNqZAhKB-0pOtOmO4wtPVoWEM");
            // 设置参数
            httppost.setEntity(new StringEntity(data, "UTF-8"));
            // 发送请求
            BasicHttpParams httpParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParams, 60 * 1000); //请求超时
            HttpConnectionParams.setSoTimeout(httpParams, 60 * 1000);         //响应超时
            hc = new DefaultHttpClient(httpParams);
            HttpResponse httpresponse = hc.execute(httppost);
            // 获取返回数据
            HttpEntity entity = httpresponse.getEntity();
            body = EntityUtils.toString(entity);
            if (entity != null) {
                entity.consumeContent();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }
        return body;
    }

    public static String post(String url, Map<String, String> paramMap) {
        String body = null;

        // Post请求
        HttpPost httppost = new HttpPost(url);
        try {
            HttpClient hc = new DefaultHttpClient();
            // 设置参数
            httppost.setEntity(new UrlEncodedFormEntity(turnParamFromMap(paramMap), HTTP.UTF_8));
            // 发送请求
            HttpResponse httpresponse = hc.execute(httppost);

            // 获取返回数据
            HttpEntity entity = httpresponse.getEntity();
            body = EntityUtils.toString(entity);
            if (entity != null) {
                entity.consumeContent();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            httppost.abort(); //终止
//            hc.getConnectionManager().closeIdleConnections(0, TimeUnit.MICROSECONDS); //再次调用确保回收
        }
        return body;
    }

    /**
     * @return java.lang.String
     * @Author raopeng
     * @Description //TODO put请求
     * @Date 2021/12/8 10:06
     * @Param [url, headers, paramMap]
     **/
    public static String put(String url, Map<String, String> headers, Map<String, String> paramMap) {
        String responseContent = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            //通过SchemeRegistry将SSLSocketFactory注册到我们的HttpClient上
            HttpPut httpPut = new HttpPut(url);
            if (headers != null) {
                for (String string : headers.keySet()) {
                    httpPut.setHeader(string, headers.get(string));
                }
            }
            List<NameValuePair> formParams = new ArrayList<NameValuePair>(); // 构建POST请求的表单参数
            for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            httpPut.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));
            HttpResponse response = httpclient.execute(httpPut);
            HttpEntity entity = response.getEntity(); // 获取响应实体
            if (entity != null) {
                responseContent = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            httpclient.getConnectionManager().shutdown();
        }
        return responseContent;
    }


    private static List<NameValuePair> turnParamFromMap(Map<String, String> paramMap) {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        for (String key : paramMap.keySet()) {
            params.add(new BasicNameValuePair(key, paramMap.get(key)));
        }
        return params;
    }

    //在redis中找不到数据的时候 才去根据币种类型 调用远程api获取当前美元价值，查到结果要先插入到redis
    public static String getCoinUSDPriceByType(String type, String toType) {
        HashMap params = new HashMap();
        params.put("amount", "1");
        params.put("symbol", type);
        if (!StringUtils.isBlank(toType)) {
            params.put("convert", toType);
        }
        String result = HttpUtils.get(CommonConstant.changeUri, null, params, CommonConstant.changeApiKey);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (jsonObject == null) {
            log.error("getCoinUSDPriceByType error jsonObject is null result:{}", result);
            return null;
        }
        JSONObject status = jsonObject.getJSONObject("status");
        if (status.getInteger("error_code") != 0) {
            log.error("getCoinUSDPriceByType error type:{}", type);
            return null;
        }
        JSONArray jsonArray = jsonObject.getJSONArray("data");
        if (jsonArray != null && jsonArray.size() > 0) {
            JSONObject dataInfo = jsonArray.getJSONObject(0);
            JSONObject quote = dataInfo.getJSONObject("quote");
            JSONObject usdInfo = null;
            if (!StringUtils.isBlank(toType)) {
                usdInfo = quote.getJSONObject(toType);
            } else {
                usdInfo = quote.getJSONObject("USD");
            }
            if (usdInfo == null) {
                log.error("usdInfo is null type:{},toType:{}", type, toType);
                return null;
            }
            String price = usdInfo.getString("price");
            System.out.println("price:" + price);
            return price;
        }
        return null;
    }


    public static String get(String url, Map<String, String> headers,Map<String, String> paramMap, Boolean openProxy ) {
        String body = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            // Get请求
            HttpGet httpget = new HttpGet(url);
            if (headers != null) {
                for (String string : headers.keySet()) {
                    httpget.setHeader(string, headers.get(string));
                }
            }
            // 设置参数
            if (paramMap != null) {
                String str = EntityUtils.toString(new UrlEncodedFormEntity(turnParamFromMap(paramMap)));
                httpget.setURI(new URI(httpget.getURI().toString() + "?" + str));
            }

            if(openProxy) {
                HttpHost proxy = new HttpHost("localhost", 7890);
                RequestConfig requestConfig = RequestConfig.custom()
                        .setProxy(proxy)
                        .setConnectTimeout(10000)
                        .setSocketTimeout(10000)
                        .setConnectionRequestTimeout(3000)
                        .build();
                httpget.setConfig(requestConfig);
            }else{
                RequestConfig requestConfig = RequestConfig.custom()
                        .setConnectTimeout(10000)
                        .setSocketTimeout(10000)
                        .setConnectionRequestTimeout(3000)
                        .build();
                httpget.setConfig(requestConfig);
            }

            // 发送请求
            HttpResponse httpresponse = httpclient.execute(httpget);
            // 获取返回数据
            HttpEntity entity = httpresponse.getEntity();
            body = EntityUtils.toString(entity);
            if (entity != null) {
                entity.consumeContent();
            }
        } catch (ParseException e) {
            log.error("http ParseException uri:{},info:{}", url, e.getMessage());
        } catch (UnsupportedEncodingException e) {
            log.error("http UnsupportedEncodingException uri:{},info:{}", url, e.getMessage());
        } catch (IOException e) {
            log.error("http IOException uri:{},info:{}", url, e.getMessage());
        } catch (URISyntaxException e) {
            log.error("http URISyntaxException uri:{},info:{}", url, e.getMessage());
        } catch (Exception e) {
            log.error("http Exception uri:{},info:{}", url, e.getMessage());
        }
        return body;
    }

    public static String get(String url, String token,Map<String, String> paramMap, String key) {
        String body = null;
        try {
            HttpClient hc = new DefaultHttpClient();
            // Get请求
            HttpGet httpget = new HttpGet(url);
            // 设置参数
            if (paramMap != null) {
                String str = EntityUtils.toString(new UrlEncodedFormEntity(turnParamFromMap(paramMap)));
                httpget.setURI(new URI(httpget.getURI().toString() + "?" + str));
            }
            if (StringUtils.isNotBlank(token)) {
                httpget.setHeader("Authorization", "Basic " + token);
            }
            if (StringUtils.isNotBlank(key)) {
                httpget.addHeader("X-CMC_PRO_API_KEY", key);
            }
            // 发送请求
            HttpResponse httpresponse = hc.execute(httpget);
            // 获取返回数据
            HttpEntity entity = httpresponse.getEntity();
            body = EntityUtils.toString(entity);
            if (entity != null) {
                entity.consumeContent();
            }
        } catch (ParseException e) {
            log.error("http ParseException uri:{},info:{}", url, e.getMessage());
        } catch (UnsupportedEncodingException e) {
            log.error("http UnsupportedEncodingException uri:{},info:{}", url, e.getMessage());
        } catch (IOException e) {
            log.error("http IOException uri:{},info:{}", url, e.getMessage());
        } catch (URISyntaxException e) {
            log.error("http URISyntaxException uri:{},info:{}", url, e.getMessage());
        } catch (Exception e) {
            log.error("http Exception uri:{},info:{}", url, e.getMessage());
        }
        return body;
    }

    /**
     * @Author 下载文件
     * @Description //TODO raopeng
     * @Date 2021/6/22 17:41
     * @Param [url, filepath]
     * @return java.lang.String
     **/
    public static void download(String url, ServletOutputStream stream ) {
        try {
            HttpClient client = HttpClients.createDefault();
            HttpGet httpget = new HttpGet(url);
            HttpResponse response = client.execute(httpget);

            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();

            /**
             * 根据实际运行效果 设置缓冲区大小
             */
            byte[] buffer = new byte[1024];
            int ch = 0;
            while ((ch = is.read(buffer)) != -1) {
                stream.write(buffer, 0, ch);
            }
            is.close();
            stream.flush();
            stream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void download(String url, FileOutputStream stream ) {
        try {
            HttpClient client = HttpClients.createDefault();
            HttpGet httpget = new HttpGet(url);
            HttpResponse response = client.execute(httpget);

            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();

            /**
             * 根据实际运行效果 设置缓冲区大小
             */
            byte[] buffer = new byte[1024];
            int ch = 0;
            while ((ch = is.read(buffer)) != -1) {
                stream.write(buffer, 0, ch);
            }
            is.close();
            stream.flush();
            stream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @Author raopeng
     * @Description //TODO post - json请求
     * @Date 2021/12/8 10:30
     * @Param [url, token, jsonStr]
     * @return java.lang.String
     **/
    public static Map<String,String>  doPostJson(String url, Map<String,String> headers, String jsonStr) {
        Map<String, String> result = new HashMap<>();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
        httpPost.setConfig(requestConfig);
        httpPost.setHeader("Content-Type", "application/json");
        headers.forEach(httpPost::setHeader);
        CloseableHttpResponse httpResponse = null;
        try {
            httpPost.setEntity(new StringEntity(jsonStr,"UTF-8"));
            httpResponse = httpClient.execute(httpPost);
            HttpEntity entity = httpResponse.getEntity();
            result.put("code", httpResponse.getStatusLine().getStatusCode()+"");
            result.put("result", EntityUtils.toString(entity));
            return result;
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    /**
     * @Author raopeng
     * @Description //TODO put - json请求
     * @Date 2021/12/8 10:30
     * @Param [url, token, jsonStr]
     * @return java.lang.String
     **/
    public static String doPutJson(String url, String token, String jsonStr) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPut httpPut = new HttpPut(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
        httpPut.setConfig(requestConfig);
        httpPut.setHeader("Content-type", "application/json");
//        httpPut.setHeader("DataEncoding", "UTF-8");
        if (StringUtils.isNotBlank(token)) {
            httpPut.setHeader("Authorization", "Basic " + token);
        }

        CloseableHttpResponse httpResponse = null;
        try {
            if (StringUtils.isNotBlank(jsonStr)) {
                httpPut.setEntity(new StringEntity(jsonStr,"UTF-8"));
            }
            httpResponse = httpClient.execute(httpPut);
            HttpEntity entity = httpResponse.getEntity();
            return  EntityUtils.toString(entity);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * @Author raopeng
     * @Description //TODO delete json 方法
     * @Date 2021/12/8 11:01
     * @Param [url, token, jsonStr]
     * @return java.lang.String
     **/
    public static String doDeleteJson(String url, String token, String jsonStr) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url);

        HttpHost proxy = new HttpHost("localhost", 7777, "https");


        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).
                setSocketTimeout(60000).
//                setProxy(proxy).
                build();
        httpDelete.setConfig(requestConfig);
        httpDelete.setHeader("Content-type", "application/json");
//        httpPut.setHeader("DataEncoding", "UTF-8");
        if (StringUtils.isNotBlank(token)) {
            httpDelete.setHeader("Authorization", "Basic " + token);
        }

        CloseableHttpResponse httpResponse = null;
        try {
            httpDelete.setEntity(new StringEntity(jsonStr,"UTF-8"));
            httpResponse = httpClient.execute(httpDelete);
            HttpEntity entity = httpResponse.getEntity();
            String result = EntityUtils.toString(entity);
            return result;
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }




    /**
     * @Author raopeng
     * @Description //TODO delete 实现 setEntrty方法
     * @Date 2021/12/8 11:07
     * @Param
     * @return
     **/
    public static class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
        public static final String METHOD_NAME = "DELETE";
        public String getMethod() { return METHOD_NAME; }

        public HttpDeleteWithBody(final String uri) {
            super();
            setURI(URI.create(uri));
        }
        public HttpDeleteWithBody(final URI uri) {
            super();
            setURI(uri);
        }
        public HttpDeleteWithBody() { super(); }
    }

    /**
     * url资源转化为file流
     * @param url
     * @return
     */
    public static File urlToFile(String url) {
        HttpURLConnection urlConn = null;
        InputStream is = null;
        File file = null;
        FileOutputStream fos = null;
        try {
            file = File.createTempFile("tmp", null);
//            URLConnection urlConn = null;
            urlConn =  (HttpURLConnection) new URL(url).openConnection();
            is = urlConn.getInputStream();
            fos = new FileOutputStream(file);
            byte[] buffer = new byte[4096];
            int length;
            while ((length = is.read(buffer)) > 0) {
                fos.write(buffer, 0, length);
            }
            return file;
        } catch (IOException e) {
            return null;
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                }
            }
        }
    }

}
